package cn.rainless.zxing.demo;

import com.google.zxing.WriterException;
import org.apache.commons.lang.StringUtils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class DeviceQrCreator {

  private static final int BACKGROUND_WIDTH = 945;
  private static final int BACKGROUND_HEIGHT = 472;

  private static final int QRCODE_SIZE = 295;
  private static final int QRCODE_TOP = BACKGROUND_HEIGHT - QRCODE_SIZE - 20;
  private static final int QRCODE_LEFT = BACKGROUND_WIDTH - QRCODE_SIZE - 20;

  private static final int LEFT_TEXT_START = 155;
  private static final int RIGHT_TEXT_START = 450;
  private static final int LINE_HEIGHT = 58;
  private static final int FONT_HEIGHT = 30;
  private static final int LINE_TOP1 = 195;
  private static final int LINE_TOP2 = LINE_TOP1 + LINE_HEIGHT;
  private static final int LINE_TOP3 = LINE_TOP2 + LINE_HEIGHT;
  private static final int LINE_TOP4 = LINE_TOP3 + LINE_HEIGHT;
  private static final int LINE_TOP5 = LINE_TOP4 + LINE_HEIGHT;
  private static final int PHONE_LINE_TOP = LINE_TOP4 + FONT_HEIGHT;

  private static final Font TITLE_FONT = new Font("Dutch801 Rm BT", Font.PLAIN, 30);
  private static final Font NORMAL_FONT = new Font("Dutch801 Rm BT", Font.PLAIN, 20);

  private DeviceQrCreator() {
  }

  public static BufferedImage createPng(DeviceInfo device) throws IOException, WriterException {
    BufferedImage image = BitMatrixUtils.readImage("/card.png");
    Graphics2D graph = image.createGraphics();
    // 抗文本锯齿
    graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    graph.setColor(Color.BLACK);
    // 绘制设备信息
    drawText(graph, device.getNo(), LEFT_TEXT_START, LINE_TOP1, TITLE_FONT);
    drawText(graph, device.getModel(), LEFT_TEXT_START, LINE_TOP2, NORMAL_FONT);
    drawText(graph, device.getSn(), LEFT_TEXT_START, LINE_TOP3);
    drawText(graph, device.getManager(), LEFT_TEXT_START, LINE_TOP4);
    drawText(graph, device.getManagerPhone(), LEFT_TEXT_START, PHONE_LINE_TOP);
    drawText(graph, device.getUsage(), RIGHT_TEXT_START, LINE_TOP2);
    drawText(graph, device.getPosition(), RIGHT_TEXT_START, LINE_TOP3);
    drawText(graph, device.getIp(), RIGHT_TEXT_START, LINE_TOP4);
    drawText(graph, device.getCheckDate(), RIGHT_TEXT_START, LINE_TOP5);
    // 绘制二维码
    BufferedImage qrcode = BitMatrixUtils.createQrcode(device.getQrCode(), QRCODE_SIZE, QRCODE_SIZE, "/logo.png");

    graph.drawImage(qrcode, QRCODE_LEFT, QRCODE_TOP, null);
    graph.dispose();
    image.flush();
    return image;
  }

  private static void drawText(Graphics2D graph, String text, int left, int top) {
    drawText(graph, text, left, top, null);
  }

  private static void drawText(Graphics2D graph, String text, int left, int top, Font font) {
    if (StringUtils.isBlank(text)) {
      return;
    }
    if (font != null) {
      graph.setFont(font);
    }
    graph.drawString(text, left, top);
  }

}
